#pragma once

#include <iostream>
#include <functional>
#include <signal.h>
#include <unistd.h>
#include <string>
#include "Socket.hpp"
#include "log.hpp"

using func_t = std::function<std::string(std::string &package)>;
// typedef std::function<std::string(const std::string &package)> func_t;

 Log lg;
class TcpServer
{
public:
    TcpServer(uint16_t port,func_t callback)
        : port_(port),callback_(callback)
    {
    }
    // TcpServer()
    // {}

    bool TcpInit()
    {
        listensock.Socket();
        listensock.Bind(port_);
        listensock.Listen();
        //  std::cout<<"Init done...."<<std::endl;
        lg(Info, "TcpInit done....");
        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);
        while (true)
        {
            uint16_t clientport;
            std::string clientip;
            int sockfd = listensock.Accept(&clientip, &clientport);
            
            if (sockfd < 0)
                break;
            lg(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", sockfd, clientip.c_str(), clientport);
            if (fork() == 0)
            {
                listensock.Closefd();
                std::string inbuffer_stream;
                while (true)
                {
                    char buffer[1028];
                    int n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_stream += buffer;
                        lg(Info, "Debug:\n%s", inbuffer_stream.c_str());
                        while (true)
                        {
                            std::string info = callback_(inbuffer_stream);
                            if(info.empty())
                                break;
                            lg(Info,"Debug->responce:\n%s",info.c_str());
                            lg(Info,"Debug->\n%s",inbuffer_stream.c_str());
                            write(sockfd,info.c_str(),info.size());
                        }
                    }
                    else if (n < 0)
                    {
                        lg(Warning, "read error,errno:%d,errstring:%s", errno, strerror(errno));
                        break;
                    }
                    else
                        break;
                }
            }
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t port_;
    Sock listensock;
    func_t callback_;
};